﻿using System.Collections.Generic;

namespace HCore
{
    public class InputCommandManager : CommandManager
    {
        private readonly List<Command> _cacheCommands;

        public InputCommandManager(HGame game) : base(game)
        {
            _cacheCommands = new List<Command>();
            _game.networkMgr.Register(PacketType.TurnData, TurnDataHandle);
        }

        private void TurnDataHandle(InputMemoryBitStream input)
        {
            int turnCount = input.ReadInt();
            int count = input.ReadInt();
            for (int i = 0; i < count; i++)
            {
                TurnData turnData = new TurnData();
                turnData.Read(input);
                AddTurnData(turnCount, turnData);
            }
        }

        public override void Dispose()
        {
            base.Dispose();
            _game.networkMgr.Unregister(PacketType.TurnData);
        }

        public override void AddUserCommand(Command command)
        {
            if (_game.inBattle)
            {
                Debug.Assert(command.playerId > 0 && command.playerId == _game.playerId);
                // 只保留一条
                _cacheCommands.Clear();
                _cacheCommands.Add(command);
            }
        }

        public override void Update(int checkSum)
        {
            ProcessInput(checkSum);
            base.Update(checkSum);
        }

        private void ProcessInput(int checkSum)
        {
            if (!_game.inBattle)
            {
                return;
            }

            if (_game.timer.frameCount % GameDefine.FRAMES_PER_TURN != 0)
            {
                return;
            }

            Command command;
            if (_cacheCommands.Count > 0)
            {
                command = _cacheCommands[0];
                _cacheCommands.RemoveAt(0);
            }
            else
            {
                command = new EmptyCommand();
                command.playerId = _game.playerId;
            }

            //发送给服务器
            TurnData turnData = GenerateTurnData(_game.timer.frameCount / GameDefine.FRAMES_PER_TURN, command);
            turnData.checkSum = checkSum;
            OutputMemeryBitStream output = new OutputMemeryBitStream();
            output.WriteByte(PacketType.TurnData);
            turnData.Write(output);
            _game.networkMgr.Send(output.GetBuffer(), output.GetByteLength());
        }

        private TurnData GenerateTurnData(int turnCount, Command command)
        {
            int index = turnCount;
            if (index < 0)
            {
                return null;
            }

            TurnData turnData = new TurnData(command.playerId, turnCount);
            turnData.AddCommand(command);
            return turnData;
        }
    }
}